#pragma once

#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

using namespace log_ns;

static const int gsockfd = -1;
static const uint16_t glocalport = 8888;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

using server_t = std::function<void(int, std::string, InetAddr)>;

class UdpServer : public nocopy
{
public:
    UdpServer(server_t func, const uint16_t &localport = glocalport)
        : _func(func), _sockfd(gsockfd), _localport(localport), _isrunning(false)
    {
    }
    void InitServer()
    {
        // AF_INET 表示 IPv4 地址，例如 127.0.0.1；AF_INET6 表示 IPv6 地址
        // SOCK_STREAM（流格式套接字/面向连接的套接字） 和 SOCK_DGRAM（数据报套接字/无连接的套接字）
        //  protocol 表示传输协议，常用的有 IPPROTO_TCP 和 IPPTOTO_UDP，分别表示 TCP 传输协议和 UDP 传输协议。
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success, sockfd:%d\n", _sockfd);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);
        local.sin_addr.s_addr = INADDR_ANY;
        // local.sin_addr.s_addr = inet_addr(_localid.c_str());

        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind create success\n");
    }
    void Start()
    {
        _isrunning = true;
        char inbuff[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuff, sizeof(inbuff) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                inbuff[n] = 0;
                InetAddr addr(peer);
                std::cout << "[ " << addr.Ip().c_str() << ":" << addr.port() << " ]" << inbuff << std::endl;
                _func(_sockfd, inbuff, addr);
            }
        }
    }
    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            ::close(_sockfd);
    }

private:
    int _sockfd;
    uint16_t _localport;
    // std::string _localid;
    bool _isrunning;
    server_t _func;
};